package com.bread.tliaswebmanagement.interceptor;

import com.bread.tliaswebmanagement.utils.CurrentHolder;
import com.bread.tliaswebmanagement.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /*String requestURI = request.getRequestURI();
        if (requestURI.contains("/login")) {
            log.info("登录请求，放行");
            //放行
            return true;
        }*/
        //省略掉登录请求的拦截，在配置中设置
        //获取令牌
        String token = request.getHeader("token");
        if (token == null || token.isEmpty()) {
            log.info("令牌为空，未登录");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        //令牌不为空，则要校验令牌
        try{
            Claims claims = JwtUtils.parseJwt(token);
            Integer id = Integer.valueOf(String.valueOf(claims.get("id")));
            CurrentHolder.setCurrentId(id);
            log.info("当前用户id为：{},将其存入ThreadLocal", id);
        } catch (Exception e) {
            log.info("令牌非法");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        log.info("令牌合法");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        CurrentHolder.remove();
        log.info("移除ThreadLocal中的用户id");
    }
}
